const request = require('../../xci/request')
const helper = require('../../xci/helper')
const auth = require('../../xci/auth')
const {email, idcardNumber} = require('../../xci/validator')

Page({
  data: {
    formName: 'loginForm',
    alignType: 'end',
    labelWidth: '160rpx',
    sendPhoneButton: '获取验证码',
    sendPhoneButtonDisabled: false,
    captchaDialogShow: false,
    captchaBase64: '',
    rule: {
      phone: {required: true, message: '请输入注册手机号'},
      phoneCaptcha: {required: true, message: '请输入手机验证码'},
      idcard: {validator: idcardNumber, message: '请输入正确的身份证号码'},
      name: {required: true, message: '请输入姓名'},
      email: {validator: email, message: '请输入正确的邮箱地址'},
    },
    userInfo: null,
    phone: '',
    phoneCaptcha: '',
    inputCaptcha: '',
    serialNumber: '',
  },
  async onLoad() {
    wx.lin.initValidateForm(this)
  },
  onShow() {
    const userInfo = auth.getTokenInfo()
    if (userInfo) {
      this.setData({
        userInfo,
        phone: userInfo.phone || '',
      })
    }
  },
  onSave() {
    wx.lin.submitForm(this.data.formName)
  },
  async onSubmit(e) {
    console.log(e.detail)
    if (e.detail.isValidate === false) return

    const openid = await auth.getOpenid()
    const result = await auth.register({...e.detail.values, wechatid: openid, serialNumber: this.data.serialNumber})

    console.log(result)
    // //页面跳转回首页
    // wx.switchTab({url: helper.getHomePagePath()})
    wx.navigateBack()
  },
  async onBuildCaptcha() {
    if (helper.isBlank(this.data.phone)) {
      await helper.showToast('请输入手机号码')
      return
    }
    if (this.data.phone.length !== 11) {
      await helper.showToast('请输入11位有效手机号码')
      return
    }

    const imgBase64 = await this.buildCaptchaCore()

    this.setData({
      inputCaptcha: '',
      captchaBase64: imgBase64,
      captchaDialogShow: true
    })
  },
  async onRebuildCaptcha() {
    const imgBase64 = await this.buildCaptchaCore()
    this.setData({
      captchaBase64: imgBase64,
    })
  },

  buildCaptchaCore() {
    this.data.serialNumber = helper.randomString(37)

    const data = {
      phone: this.data.phone,
      serialNumber: this.data.serialNumber
    }

    return this.captchaBase64(data)
  },
  /**
   * 获取验证码base64编码
   * @param data 请求数据
   * @return {Promise<string>}
   */
  captchaBase64(data) {
    return request.post('/api/mini/user/buildPhoneCaptcha', data, {responseType: 'arraybuffer'})
            .then(res => `data:image/png;base64,${wx.arrayBufferToBase64(res)}`)
  },
  async onSendPhoneCaptcha(e) {
    // console.log(e)
    if (helper.isBlank(this.data.inputCaptcha)) {
      await helper.showToast('请输入验证码')
      return
    }

    this.resetTime(60)

    const data = {
      phone: this.data.phone,
      serialNumber: this.data.serialNumber,
      phoneCaptcha: this.data.inputCaptcha
    }
    const result = await request.post('/api/mini/user/sendPhoneCaptcha', data)
    console.log(result)
  },
  resetTime(total) {
    const self = this
    let text = '', disabled
    helper.countDown(total, val => {
      if (val === 0) {
        disabled = false
        text = '获取验证码'
      } else {
        disabled = true
        text = `${val}秒后重发`
      }
      self.setData({
        sendPhoneButton: text,
        sendPhoneButtonDisabled: disabled
      })
    })
  },

})